package ewan.android.droidjockey;

import java.util.List;

import ewan.android.droidjockey.R;

import ewan.android.droidjockey.MusicRetriever.Item;

import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;

public class AlbumListFragment extends ListFragment {

	enum State {
		albumView, // The songlist is displaying albums
		SongView, // The songlist is displaying songs
	};

	static State mState;
	static String album;

	private int currentPosition = 0;
	Button nowPlaying;
	Button backButton;
	ProgressBar progress;
	boolean threadWait = false;
	boolean created = false;
	static boolean goBack = false;

	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
	}
	
	public void onDestroyView(){
		super.onDestroyView();
		//ui.cancel(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
		if (mState == null) {
			mState = State.albumView;
		}
		View songList = inflater.inflate(R.layout.songlist, container, false);
		Context ctx = (Context) AlbumListFragment.this.getActivity();
		// Inflate the layout for this fragment

		backButton = (Button) songList.findViewById(R.id.goback);
		nowPlaying = (Button) songList.findViewById(R.id.playing);
		nowPlaying.setSelected(true); 
		nowPlaying.setEllipsize(TruncateAt.MARQUEE); 
		nowPlaying.setSingleLine(true);
		backButton.setTextColor(Color.parseColor("#696969"));
		
		if (mState == State.albumView) {
			backButton.setText("All Albums");
			setListAdapter(new ArrayAdapter<String>(ctx, R.layout.song_item,
				MusicRetriever.getAlbums()));
		}
		
		else {
			backButton.setText(album);
			backButton.setTextColor(Color.parseColor("#FFFFFF"));
			setListAdapter(new ArrayAdapter<String>(ctx, R.layout.song_item,
					MusicRetriever.getSongsByAlbum(album)));
		}
		
		progress = (ProgressBar) songList.findViewById(R.id.progress);
		try {
			nowPlaying.setText(MusicRetriever.getCurrentSong().getTitle().toString());
			progress.setMax((int) MusicRetriever.getCurrentSong().getDuration());
		} catch (Exception e) {
			System.out.println("The Exception");
			nowPlaying.setText("Now Playing");
			e.printStackTrace();
		}
		nowPlaying.setOnClickListener(new OnClickListener() {

			public void onClick(View target) {

				if (target == nowPlaying) {
					Intent intent = new Intent();
					AlbumListFragment.this.getActivity().setResult(1, intent);
					AlbumListFragment.this.getActivity().finish();
			}
			
		}
		});
		backButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View target) {
				Context ctx = (Context) AlbumListFragment.this.getActivity();
				
				if (target == backButton) {
					if (mState == State.SongView) {
						backButton.setText("All Albums");
						setListAdapter(new ArrayAdapter<String>(ctx, R.layout.song_item,
								MusicRetriever.getAlbums()));
						backButton.setTextColor(Color.parseColor("#696969"));
						mState = State.albumView;
					}
				}
				
			}
			
		});
		if (!thread.isAlive() && !(thread.isInterrupted())){
			try {
				thread.start();
			} catch(Exception e)
			{}
		}
		return songList;
	}
	
	

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		if (mState == State.albumView) {
			backButton.setTextColor(Color.parseColor("#FFFFFF"));
			Context ctx = (Context) AlbumListFragment.this.getActivity();
			album = l.getItemAtPosition(position).toString();
			backButton.setText(album);
			setListAdapter(new ArrayAdapter<String>(ctx, R.layout.song_item,
					MusicRetriever.getSongsByAlbum(l.getItemAtPosition(position).toString())));
			mState = State.SongView;

		} else if (mState == State.SongView) {
			Context ctx = (Context) AlbumListFragment.this.getActivity();
			MusicRetriever.mainSongList = false;
			MusicRetriever.usingGenPlaylist = false;
			MusicRetriever.usingPlaylist = true;
			MusicRetriever.playlist.clear();
			MusicRetriever.playlist.addAll(MusicRetriever.tempPlaylist);
			currentPosition = position;
			List<Item> s = MusicRetriever.getPlaylist();
			Item toPlay = s.get(currentPosition);
			Intent i = new Intent(MusicService.ACTION_URI);
			
			i.putExtra("Position", currentPosition);
			ctx.startService(i);
			Intent intent = new Intent();
			mState = State.albumView;
			AlbumListFragment.this.getActivity().setResult(1, intent);
			if (MusicRetriever.shuffle){
				MusicRetriever.shuffle = false;
				ctx.startService(new Intent(MusicService.ACTION_SHUFFLE));
			}
			AlbumListFragment.this.getActivity().finish();
		}
	}
	
	
	Thread thread = new Thread() {
		public synchronized void run() {

			while (true) {
				try {

						while (MusicService.State.Playing != null) {
							
							try {
								Message position = new Message();
								position.what = MusicService.mPlayer
										.getCurrentPosition();
								threadHandler.sendMessage(position);
								if (MusicService.State.Playing != null) {
									if (!nowPlaying.getText().equals(
											MusicRetriever.getCurrentSong()
													.getTitle().toString())) {

										Message update = new Message();
										update.what = 0;
										UIHandler.sendMessage(update);

									}
								}
							} catch (NullPointerException e) {
							} catch (Exception e) {
								e.printStackTrace();
							}
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								Thread.currentThread().interrupt();
						        break;
							}
						}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						Thread.currentThread().interrupt();
				        break;
					}
				} catch (IndexOutOfBoundsException e) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						Thread.currentThread().interrupt();
				        break;
					}
				}
			}
		}

	};
		
		public synchronized void onPause() {
			super.onPause();
		}
		
		public synchronized void onDestroy() {
			super.onDestroy();
			thread.interrupt();
		}
		
		public synchronized void onResume() {
			System.out.println("Resuming");
			super.onResume();
			try {
				progress.setMax((int) MusicRetriever.getCurrentSong().getDuration());
				Message position = new Message();
				position.what = MusicService.mPlayer.getCurrentPosition();
				threadHandler.sendMessage(position);
			} catch (Exception e) {
			}
		}
		
		
		public Handler UIHandler = new Handler() {

			public synchronized void handleMessage(Message msg) {
				if (msg.what == 0) {
					try {
					nowPlaying.setText(MusicRetriever.getCurrentSong().getTitle().toString());
					progress.setMax((int) MusicRetriever.getCurrentSong().getDuration());
					} catch (Exception e) {}
				}
			}
		};


		private Handler threadHandler = new Handler() {

			public synchronized void handleMessage(Message msg) {
				progress.setProgress(msg.what);
			}
		};

		
}